<!-- 登录 -->
<template>
  <div class="muse-login-wrapper">
    <!-- logo等 -->
    <div class="company-logo-wrapper">
      <img class="logo-full" src="@/assets/images/login-page-logo-w.png" />
      <!-- <img class="company-logo" src="@/assets/images/logo-big-white.png" />
      <p class="company-name">精策云</p> -->
    </div>

    <div class="muse-login-function-container">
      <div class="strechable-right">
        <div class="muse-login-field">
          <Spin size="large" fix v-if="isLoading"></Spin>
          <!-- 容器 -->
          <div class="login-content">
  
            <!-- 欢迎字符 -->
            <div class="login-content-title">
              <h2>欢迎<span>使用</span></h2>
              <h4>精策云</h4>
            </div>
  
            <div class="login-tab-wrapper">
              <div class="login-tab-header">
                <p class="login-tab-option" :class="{ 'active': state.currentLoginType == 1 }" @click="handleSwitchLoginType(1)">账户登录</p>
                <p class="login-tab-option" :class="{ 'active': state.currentLoginType == 2 }" @click="handleSwitchLoginType(2)">手机号登录</p>
              </div>
              <div class="login-tab-rail">
                <!-- 账户登录 -->
                <div class="login-tab-content" :style="{ transform: `translateX(${state.currentLoginType == 1 ? 0 : -420}px)`, opacity: `${state.currentLoginType == 1 ? 1 : 0 }` }">
                  <!-- 账号 -->
                  <div class="form-item">
                    <div class="form-item_label">
                      <span class="label">账号</span>
                      <span class="error" v-if="state.isNameError"><IconFont icon="tishi" size="16" style="color: var(--muse-danger-color)" />账号错误！</span>
                    </div>
                    <div class="input-row" :class="{ 'active': state.focusTarget === 'username', 'valuable': username, 'error': state.isNameError }" @click.stop="handleInputFocus('username')">
                      <div class="prefix">
                        <IconFont icon="user-single-solid" size="20" />
                      </div>
                      <div class="input">
                        <input v-model.trim="username" placeholder="请输入账号"/>
                      </div>
                    </div>
                  </div>
                  <!-- 密码 -->
                  <div class="form-item">
                    <div class="form-item_label">
                      <span class="label">密码</span>
                      <span class="error" v-if="state.isPwdError"><IconFont icon="tishi" size="16" style="color: var(--muse-danger-color)" />密码错误！</span>
                    </div>
                    <div class="input-row" :class="{ 'active': state.focusTarget === 'password', 'valuable': password, 'error': state.isPwdError }" @click.stop="handleInputFocus('password')">
                      <div class="prefix">
                        <IconFont icon="lock" size="20" />
                      </div>
                      <div class="input">
                        <input name="password" autocomplete="new-password" v-model.trim="password" placeholder="请输入密码" :type="state.showPlaintext === true ? 'text' : 'password'"/>
                        <input name="password" autocomplete="new-password" type="password" style="display: none;" />
                      </div>
                      <div class="suffix show-plain-text" :class="{ 'active': state.showPlaintext === true }" @click="state.showPlaintext = !state.showPlaintext">
                        <IconFont :icon="state.showPlaintext === true ? 'eye-open' : 'eye-close'" size="20" />
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 手机号登录 -->
                <div class="login-tab-content" :style="{ transform: `translateX(${state.currentLoginType == 1 ? 420 : -420}px)`, opacity: `${state.currentLoginType == 2 ? 1 : 0 }` }">
                  <!-- 手机号 -->
                  <div class="form-item">
                    <div class="form-item_label">
                      <span class="label">手机号</span>
                      <span class="error" v-if="state.isMobileError"><IconFont icon="tishi" size="16" style="color: var(--muse-danger-color)" />手机号错误！</span>
                    </div>
                    <div class="input-row" :class="{ 'active': state.focusTarget === 'mobile', 'valuable': mobile, 'error': state.isMobileError }" @click.stop="handleInputFocus('mobile')">
                      <div class="prefix">
                        <IconFont icon="mobile" size="20" />
                      </div>
                      <div class="input">
                        <input v-model.trim="mobile" placeholder="请输入手机号"/>
                      </div>
                    </div>
                  </div>
  
                  <!-- 验证码 -->
                  <div class="form-item">
                    <div class="form-item_label">
                      <span class="label">验证码</span>
                      <span class="error" v-if="state.isCaptchaError"><IconFont icon="tishi" size="16" style="color: var(--muse-danger-color)" />手机号错误！</span>
                    </div>
                    <div class="input-row" :class="{ 'active': state.focusTarget === 'captcha', 'valuable': mobile, 'error': state.isCaptchaError }">
                      <div class="prefix">
                        <IconFont icon="captcha" size="20" />
                      </div>
                      <div class="input captcha-wrapper">
                        <input v-model.trim="verifyCode" placeholder="请输入验证码" @click.stop="handleInputFocus('captcha')"/>
                        <div class="slide-verify-wrapper" v-if="state.showCountDown == true">
                          <p class="get-captcha count-down">（{{ state.countDown }}）秒后重新获取</p>
                        </div>
                        <slideVerify class="slide-verify-wrapper" ref="slideVerifyRef" @captchaFn="onCaptchaSuccess" v-if="state.showCountDown == false">
                          <p class="get-captcha" @click.stop="handleGetCaptcha">获取验证码</p>
                        </slideVerify>
                      </div>
                    </div>
                  </div>
  
  
  
                </div>
              </div>
            </div>
  
            <!-- 自动登录 -->
            <div class="form-item auto-login">
              <div class="check-box-wrapper">
                <Checkbox v-model="autoLogin" size="large">自动登录</Checkbox>
              </div>
              <a class="blue-color forget-password" @click="retrievePassword()">忘记密码</a>
            </div>

            <!-- 登录按钮 -->
            <div class="login-button-field">
              <a class="login-button" @click="handleSubmit">
                登录
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import { mapActions } from "vuex";
import mixins from "../mixins";
import slideVerify from "@/components/slideVerify";
// import { SlideVerify } from "vue-monoplasty-slide-verify";

import { frameInRoutes } from "@/router/routes";
import BasicLayout from "@/layouts/basic-layout";

import { encryptByDES, decryptByDES } from "@/utils/encrypFile.js";

import {
  getSlideVerifyImage,
  ValidSlideVerifyImage, // 上传滑块位置
  SendVerifyMobileSms, // 获取验证码
} from "@/api/common.js";

export default {
  mixins: [mixins],
  components: { slideVerify },
  data() {
    return {
      autoLogin: true,
      count: 60,
      isLoading: false,

      username: '', //用户名
      password: '', //密码

      mobile: '', //手机号
      verifyCode: '', //验证码

      state: {
        isPwdError: false,
        isNameError: false,
        isMobileError: false,
        focusTarget: null,
        showPlaintext: false,
        currentLoginType: 1, //登录类型

        showCountDown: false, //显示倒计时
        countDown: 0, //倒计时
        countDownInstance: null, //计时器
      }
    };
  },
  mounted() {
    setTimeout(() => {
      window.addEventListener("keydown", this.keyDown);
    }, 24)
  },
  beforeDestroy() {
    window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    ...mapActions("admin/account", ["login"]),

    /**
     * @description 账号密码登录
     */
    async handleSubmit() {
      let valid = await this.beforeLogin();
      if (valid) {
        this.isLoading = true;
        let params = {
          username: this.state.currentLoginType == 1 ? this.username : this.mobile,
          password: this.state.currentLoginType == 1 ? this.password : this.verifyCode,
          type: this.state.currentLoginType,
        }
        console.log(params)
        this.login(params).then(() => {
          this.isLoading = false;
          this.afterLogin();
        }).catch(() => {
          this.isLoading = false;
        });
      }
    },

    //获取验证码
    handleGetCaptcha() {
      if (!this.mobile) {
        this.$Message.error('请输入手机号');
        return;
      }
      this.$refs.slideVerifyRef.innuser();
    },

    /**
     * @description 图片验证码验证成功
     */
    async onCaptchaSuccess() {
      let data = await getSlideVerifyImage();
      let verifyParams = {
        mobile: this.mobile,
      };
      let res = await SendVerifyMobileSms(verifyParams);
      this.$Message.success('验证码已发送');
      this.state.showCountDown = true;
      this.state.countDown = 60;
      this.createCountDown();
    },
    
    /**
     * @description 注册账号
     */
    regiserNewAccount() {
      this.$router.push({
        name: "register",
      });
    },

    /**
     * @description 忘记密码
     */
    retrievePassword() {
      this.$router.push({
        path: "/retrievePassword",
      });
    },

    /**
     * @description 输入框聚焦事件
     */
    handleInputFocus(targetName) {
      this.state.focusTarget = targetName;
    },

    /**
     * @description 切换登录类型
     * @param type 1账户密码 2手机号码
     */
    handleSwitchLoginType(type) {
      this.state.focusTarget = '';
      if (type == 1) {
        this.username = '';
        this.password = '';
      }
      if (type == 2) {
        this.mobile = '';
        this.verifyCode = '';
      }
      this.state.currentLoginType = type;
    },

    /**
     * @description 生产倒计时
     */
    createCountDown() {
      this.state.countDownInstance = setInterval(() => {
        this.state.countDown--;
        if (this.state.countDown == 0) {
          this.clearCountDown(); //清理倒计时
        }
      }, 1000)
    },

    /**
     * @description 销毁倒计时
     */
    clearCountDown() {
      clearInterval(this.state.countDownInstance);
      this.state.showCountDown = false;
    },

    /**
     * @description 登录前步骤
     */
    beforeLogin() {
      const _that = this;
      return new Promise(resolve => {
        let valid = checkForm();
        resolve(valid);
      })

      /**
       * @description 表单检查函数
       */
      function checkForm() {
        if (_that.state.currentLoginType == 1) {
          if (!_that.username) {
            _that.$Message.warning('请输入账号');
            return false;
          }
          if (!_that.password) {
            _that.$Message.warning('请输入密码');
            return false;
          }
        } else if (_that.state.currentLoginType == 1) {
          if (!_that.mobile) {
            _that.$Message.warning('请输入手机号');
            return false;
          }
          if (_that.$Regulars.mobile(_that.mobile) === false) {
            _that.$Message.warning('请输入正确的手机号');
            return false;
          }
          if (!_that.verifyCode) {
            _that.$Message.warning('请输入验证码');
            return false;
          }
        }
        return true;
      }
    },

    /**
     * @description 登录后续
     */
    afterLogin() {
      let meta = {
        auth: true,
      };
      let routes = [
        {
          path: "/",
          name: "home",
          redirect: {
            name: `homepage`,
          },
          meta,
          component: BasicLayout,
          children: [
            {
              path: "/home",
              name: `homepage`,
              meta: {
                ...meta,
                title: "首页",
                closable: false,
              },
              component: () => import("@/pages/home"),
            },
          ],
        },
      ];
      this.$router.addRoutes(routes);
      // 完整的 frameInRoutes，更新 vuex 的数据
      const newRoutes = frameInRoutes.concat(routes);
      this.$store.commit("admin/page/init", newRoutes);
      console.log(newRoutes, "newRoutes");
      // return;
      // 重定向对象不存在则返回顶层路径
      this.$router.replace(this.$route.query.redirect || "/home");
    },

    /**
     * @description 回车登录
     * @param e 
     */
    keyDown(e) {
      if (e.keyCode == 13) {
        console.log(123)
        this.handleSubmit();
      }
    }
  },
};
</script>

<style lang="less" scoped>
@import '../../../assets/muse_theme/less/pages/login-index.less';
</style>
